package vsqlbuilder.logic;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import vsqlbuilder.logic.postgresql.connection;

public class Table {

	private String name;
	public List<Column> columns;
	private Schema ownerSchema;

	public Table(String tableName, Schema owner) {
		name = tableName;
		this.ownerSchema = owner;
		this.columns = new ArrayList<Column>();
	}

	public String getName() {
		return this.name;
	}

	public String getSchemaName() {
		return this.ownerSchema.getName();
	}

	public boolean getTableStructure(connection tempOpenconnection) {
		// Add Columns for table from postgresql
		boolean value = true;
		Column tempcol = null;
		if (tempOpenconnection.isOpenConnection()) {
			
			String sqltemp ="SELECT column_name as column, data_type as datatype, is_nullable as isnull FROM information_schema.columns WHERE lower(table_schema)=lower('"
				+ ownerSchema.getName()
				+ "') AND lower(table_name)=lower('"
				+ this.name 
				+"')";
			
			if (tempOpenconnection.execSQL(sqltemp)) {
				try {
					while (tempOpenconnection.resultsetDB.next()) {

						tempcol = new Column(this,
								tempOpenconnection.resultsetDB
										.getString("column"));

						// TODO [medium]: Define here value of this:
						// setIsKey(valor);
						tempcol.setDataType(tempOpenconnection.resultsetDB
								.getString("datatype"));
						

						if (tempOpenconnection.resultsetDB
								.getString("isnull").compareToIgnoreCase("yes")==0) {
							tempcol.setIsNotNull(false);
						} else {
							tempcol.setIsNotNull(true);
						}

						this.columns.add(tempcol);
					}
				} catch (SQLException se) {
					value = false;
					System.out
							.println("We got an exception while creating reverse ingenieering table structure "
									+ "shouldn't happen: we've done something really bad.");
					se.printStackTrace();
					System.exit(1);
				}
			}
			tempOpenconnection.closeSQL();
		} else {
			value = false;
		}
		return value;
	}

	// toString method returns the string to be displayed for a table node in a
	// JTree
	public String toString() {
		return this.name;
	}

	// return number of columns of table
	public int getColsNumber() {
		return this.columns.size();
	}

	public Column getColumn(int i) {
		return this.columns.get(i);
	}

}
